package com.dongdongshop.front.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.front.pojo.TbContent;
import com.dongdongshop.front.service.ContentService;
import com.dongdongshop_util.RedisUtils;
import com.dongdongshop_util.Result;
import com.dongdongshop_util.ResultEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("content")
public class ContentController {

    private final Logger logger = LoggerFactory.getLogger(ContentController.class);

    @Reference(check = false,timeout = 50000)
    private ContentService contentService;
    @Autowired
    private RedisTemplate redisTemplate;

    //获取index页面数据
    @ResponseBody
    @RequestMapping("getContentByContentIdAndNumber")
    public Result getContentByContentIdAndNumber(Long categoryId,Integer number){
        List<TbContent> contentList = null;
        try {
            if (redisTemplate.boundHashOps(RedisUtils.TBCONTENT).hasKey(RedisUtils.CATEGORY+categoryId)){
                contentList = (List<TbContent>) redisTemplate.boundHashOps(RedisUtils.TBCONTENT).get(RedisUtils.CATEGORY+categoryId);
            }else {
                contentList = contentService.getContentByContentIdAndNumber(categoryId,number);
                redisTemplate.boundHashOps(RedisUtils.TBCONTENT).put(RedisUtils.CATEGORY+categoryId,contentList);
                redisTemplate.boundHashOps(RedisUtils.TBCONTENT).expire(5, TimeUnit.MINUTES);
            }
            return Result.success(ResultEnum.SUCCESS,contentList);
        }catch (Exception e){
            logger.error(String.valueOf(ResultEnum.FAIT),e);
            return Result.response(ResultEnum.FAIT);
        }
    }
}
